<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">

          <a-col    :md="3" :sm="6">
            <a-form-item label="区域名称">
              <a-select placeholder="请选择区域" v-model="queryParam.areaId" :options="areaIdOptions" ></a-select>
            </a-form-item>
          </a-col>

          <a-col :md="3" :sm="6">
            <a-form-item label="区号">
              <a-input placeholder="请输入区号" v-model="queryParam.areaCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col    :md="3" :sm="6">
            <a-form-item label="车位编号">
              <a-input placeholder="请输入车位编号" v-model="queryParam.parkNumber"></a-input>
            </a-form-item>
          </a-col>
          <a-col    :md="3" :sm="6">
            <a-form-item label="停车状态">
              <a-select v-model="queryParam.parkStatus" placeholder="请选择停车状态">
                <a-select-option value>请选择停车状态</a-select-option>
                <a-select-option value="0">空闲</a-select-option>
                <a-select-option value="1">占用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="停放车牌号">
              <a-input placeholder="请输入车牌号" v-model="queryParam.plateNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="绑定月租">
              <a-input placeholder="请输入绑定月租" v-model="queryParam.monthlyCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="4">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button style="margin-right: 6px" type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button
          @click="handleAdd"
          type="primary"
          icon="plus"
          v-has="'month:add'"
      >新增</a-button>

      <a-button    type="primary" icon="download" style="margin-left: 8px;left: 15px" @click="handleExportXls('车位管理表')" v-has="'month:export'">导出</a-button>
      <a-dropdown    v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-has="'month:delete'">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <div>
      <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          @change="handleTableChange"
          :scroll="{ x: 1400}"
          style="word-break: break-all"
      >
        <!--        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"-->
        <span slot="action" slot-scope="text, record">
           <a @click="handleDetail(record)">详情</a>
           <a-divider    type="vertical"/>
          <a-popconfirm    title="确定删除吗?" @confirm="() => handleDelete(record.id)" v-has="'month:delete'">
            <a>删除</a>
          </a-popconfirm>
        </span>

      </a-table>
    </div>
    <parking-space-edit-modal ref="editModalForm" @ok="modalFormOk"></parking-space-edit-modal>
    <parking-s-pace-add-modal ref="addModalForm" @ok="modalFormOk"></parking-s-pace-add-modal>
    <parking-space-delay-modal ref="delayModalForm" @ok="modalFormOk"></parking-space-delay-modal>
    <parking-space-modal-detail ref="detailModalForm"></parking-space-modal-detail>
  </a-card>
</template>

<script>

import ParkingSpaceEditModal from "./modules/ParkingSpaceEditModal"
import ParkingSPaceAddModal from './modules/ParkingSpaceAddModal'
import ParkingSpaceDelayModal from "./modules/ParkingSpaceDelayModal";
import ParkingSpaceModalDetail from "./modules/ParkingSpaceModalDetail";
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, getAction, downFile} from '@api/manage'
import {filterObj} from '@/utils/util';
import { getMonthlyParkInfoList } from '@api/api'

export default {
  name: "ParkingSpace",
  mixins: [JeecgListMixin],
  components: {
    ParkingSpaceEditModal,
    ParkingSPaceAddModal,
    ParkingSpaceDelayModal,
    ParkingSpaceModalDetail
  },
  data() {
    return {

      // 表头
      columns: [
        {
          title: '所在区域',
          align: "center",
          dataIndex: 'areaName',
          width: 150
        },
        {
          title: '区号',
          align: "center",
          dataIndex: 'areaCode',
          width: 150
        },
        {
          title: '车位编号',
          align: "center",
          dataIndex: 'parkNumber',
          width: 120
        },
        {
          title: '月租编号',
          align: "center",
          dataIndex: 'monthlyCode',
          width: 120
        },
        {
          title: '车位类型',
          align: "center",
          dataIndex: 'spaceType',
          width: 120,
          customRender: function (t, r, index) {
            if(t===1||t==="1")
            {
              return '标准车位';
            }
            if(t===2||t==="2")
            {
              return "子母车位";
            }
            if(t===3||t==="3")
            {
              return "预约车位";
            }
            return ""
          }
        },
        {
          title: '当前停放车辆',
          align: "center",
          dataIndex: 'plateNo',
          width: 150
        },
        {
          title: '停车状态',
          align: 'center',
          dataIndex: 'parkStatus',
          width: 150,
          customRender: function (t, r, index) {
            if(t===0||t==="0")
            {
              return '空闲';
            }
            if(t===1||t==="1")
            {
              return "占用";
            }
            return ""
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          width: 180,
          scopedSlots: {customRender: 'action'},
        }
      ],
      url: {
        list: "/parkCar/parkNumber/newlist",
        delete: "/parkCar/parkNumber/deleteNew",
        exportXlsUrl: "/parkCar/parkNumber/exportXlsNew",
        carTypeList: "/ConfigCarType/configCarType/parkCarTypeList",
        getParkInfos: "/parking/parkInfo/parkInfoList",
        areaList:"/area/parkAreaInfo/getAreaInfos",
      },
      queryParam: {
        "areaId":"",
        "endTime_begin": "",
        "endTime_end": "",
        "plateNo": "",
        "parkNumber": "",
        "carTypeId": "",
        "type": "-1",
      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      CarTypeOptions: [{value: '', label: '请选择车辆类型'}],
      areaIdOptions:[{label:'请选择区域',value:""}],
    }
  },
  computed: {
  },
  created() {
    this.keyupEnter();
    this.getParkInfo();
  },
  mounted() {
  },
  methods: {

    // 查询车场区域
    getParkInfo() {
      this.areaIdOptions = [{ value: '', label: '请选择区域' }]
      this.queryParam.areaId = ''
      this.loadAreaList()
    },

    loadParkInfo(){
      const that = this
      getMonthlyParkInfoList().then((res)=>{
        if(res.result){
          that.parkInfos = [{label:'请选择车场',value:''}]
          res.result.forEach(parkInfo=>{
            that.parkInfos.push({
              label:parkInfo.parkName,
              value:parkInfo.parkCode
            })
          })
        }
      })
    },
    loadAreaList(){
      const that = this
      if(!this.url.areaList)
      {
        this.$message.error("请设置this.url.areaList属性!")
        return
      }
      this.loading=true
      getAction(this.url.areaList,{}).then(res=>{
        if(res.success){
          that.areaIdOptions = [{value:"",label:'请选择区域'}]
          res.result.forEach(area=>{
            that.areaIdOptions.push({
              value:area.id,
              label:area.areaName
            })
          })
        }else {
          this.$message.error(res.message);
        }
        that.loading = false
      })
    },
    bindPlantNo(record) {
      this.$refs.editModalForm.edit(record)
      this.$refs.editModalForm.title = "绑定车牌";
      this.$refs.editModalForm.disableSubmit = false;
    },
    handleDelay(record) {
      this.$refs.delayModalForm.edit(record)
      this.$refs.delayModalForm.title = "车位延期";
      this.$refs.delayModalForm.disableSubmit = false;
    },
    handleAdd: function (record) {
      this.$refs.addModalForm.edit(record)
      this.$refs.addModalForm.title = "新增车位";
      this.$refs.addModalForm.disableSubmit = false;
    },
    handleDetail: function (record) {
      this.$refs.detailModalForm.edit(record);
      this.$refs.detailModalForm.title = "详情";
      this.$refs.detailModalForm.disableSubmit = true;
    },
    daysBetween(sDate1, sDate2) {
      let time1 = Date.parse(new Date(sDate1).toDateString());
      let time2 = Date.parse(new Date(sDate2).toDateString());
      let nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24));
      return nDays;
    },

    handleExportXls(fileName) {

      let param = {...this.queryParam};
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        param.endTime_begin = this.queryParam.endTime_begin + " 00:00:00";
        param.endTime_end = this.queryParam.endTime_end + " 23:59:59";
        param.plateNo = this.queryParam.plateNo;
      }
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end === "") {
        this.$message.error("请选择结束时间")
        return
      }
      if (this.queryParam.endTime_begin === "" && this.queryParam.endTime_end !== "") {
        this.$message.error("请选择开始时间")
        return
      }
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        if (this.queryParam.endTime_begin > this.queryParam.endTime_end) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {

        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')

        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }
      })
    },

    onChangeStartTime(date, dateString) {
      this.queryParam.endTime_begin = dateString;
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.endTime_end = dateString;
    },

    loadData(arg) {
      const that = this
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      let params = this.getQueryParams();
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          if(res.result){
            that.dataSource = res.result.records;
            that.ipagination.total = res.result.total;
          }else {
            that.dataSource = []
            that.ipagination.total = 0;
          }
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        that.loading = false;
      })
    },

    searchQuery() {
      let startTime = this.queryParam.endTime_begin;
      let endTime = this.queryParam.endTime_end;
      if (startTime !== "" && endTime !== "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }
      if (startTime === "" && endTime !== "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime !== "" && endTime === "") {
        this.$message.error("请选择结束时间");
        return
      }
      this.loadData(1);
    },
    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        param.endTime_begin = this.queryParam.endTime_begin + " 00:00:00";
        param.endTime_end = this.queryParam.endTime_end + " 23:59:59";
      }
      return filterObj(param);
    },

    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.deleteBatch, {
              ids: ids
            }).then((res) => {
              if (res.success || res.code == 200) {
                that.$message.success(res.message || res.msg);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message || res.msg);
              }
            });
          }
        });
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    keyupEnter() {
      // eslint-disable-next-line no-unused-vars
      document.onkeydown = e => {
      }
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
